package com.lu.banktrade.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.lu.banktrade.feign.UserClient;
import com.lu.banktrade.pojo.entity.User;
import com.lu.banktrade.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * springboot提供的登录拦截器
 * @author L
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {


    private  static final ThreadLocal<Integer> userId = new ThreadLocal<>();

    @Autowired
    @Lazy
    private UserClient userClient;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (Objects.isNull(token)||token.isEmpty()) {
            writeErrorResponse(response,"请先登录");
            return false;
        }


        Boolean fal = userClient.loginVerify(token);

        //如果用户解析用户成功则把用户id保存到ThreadLocal中
        if (fal){
            User user = userClient.getUser(token);
            userId.set(user.getUid());
        }
        return fal;
    }
    private static void writeErrorResponse(HttpServletResponse sResponse,String msg) throws IOException {
        //设置UTF-8编码
        sResponse.setContentType("application/json;charset=utf-8");
        sResponse.setCharacterEncoding("UTF-8");
        //设置响应状态码
        sResponse.setStatus(403);
        PrintWriter writer = sResponse.getWriter();
        ResultUtil fail = ResultUtil.fail(msg);
        //使用fastjson把对象转成json字符串
        writer.write(JSONObject.toJSONString(fail));
    }

}
